package com.wqj.kyee.gps.ui

import android.animation.*
import android.app.Activity
import android.app.ActivityOptions
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.*
import android.os.Bundle
import android.os.IBinder
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.animation.AnticipateOvershootInterpolator
import android.view.animation.BounceInterpolator
import android.widget.ImageView
import android.widget.Toast
import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder
import com.wqj.kyee.gps.CarAngleActivity
import com.wqj.kyee.gps.R
import com.wqj.kyee.gps.bluetooth.BluetoothUI
import com.wqj.kyee.gps.bluetooth.ble.BluetoothLeService
import com.wqj.kyee.gps.layout.CircleMenuLayout.OnMenuItemClickListener
import com.wqj.kyee.gps.nav.MapActivity
import com.wqj.kyee.gps.service.NMEAParserService
import com.wqj.kyee.gps.util.Constants
import com.wqj.kyee.gps.util.ToastUtil
import kotlinx.android.synthetic.main.activity_ui_main.*
import kotlinx.android.synthetic.main.app_bar_ui_main.*
import kotlinx.android.synthetic.main.content_ui_main.*
import org.jetbrains.anko.find


class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, OnMenuItemClickListener{

    private val mMainMenuItemTexts = arrayOf("帮助","卫星信息","姿态信息","蓝牙连接", "地图导航")
    private val mMainMenuItemImgs = intArrayOf(R.drawable.ic_menu_help, R.drawable.ic_menu_satellite_info, R.drawable.ic_menu_posture, R.drawable.ic_menu_bluetooth, R.drawable.ic_menu_navigaton)

    private var TAG : String = "MainActivity"

    private var mBluetoothAdapter: BluetoothAdapter? = null
    private val REQUEST_ENABLE_BT = 1

    private lateinit var mCenterMenu : ImageView

    override fun itemClick(view: View?, pos: Int) {

        var scaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 1f, 0.8f)
        var scaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 1f, 0.8f)

        var scaleX_2 = PropertyValuesHolder.ofFloat("scaleX", 0.8f, 0.8f, 1.0f)
        var scaleY_2 = PropertyValuesHolder.ofFloat("scaleY", 0.8f, 0.8f, 1.0f)

        var anim1 = ObjectAnimator.ofPropertyValuesHolder(view, scaleX, scaleY)
        var anim2 = ObjectAnimator.ofPropertyValuesHolder(view, scaleX_2, scaleY_2)


        var animSet = AnimatorSet()
        animSet.setDuration(100)
        animSet.setInterpolator(AnticipateOvershootInterpolator())
        animSet.play(anim2).after(anim1)
       //animSet.start()


        when (pos) {
            0 -> {  //Help

                animSet.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator?) {
                        var dialogBuilder = NiftyDialogBuilder.getInstance(this@MainActivity)
                        dialogBuilder
                                .withTitle(resources.getString(R.string.help_title))
                                .withMessage(resources.getString(R.string.help_description))
                                .withTitleColor(resources.getColor(R.color.colorPrimaryDark))
                                .withDialogColor(resources.getColor(R.color.colorPrimary))
                                .withIcon(resources.getDrawable(R.drawable.ic_menu_help))
                                .withEffect(Effectstype.Slit)
                                .show()
                    }
                })

                animSet.start()
            }

            1 -> {  // Satellite Info
                //Toast.makeText(this, mMainMenuItemTexts[1],
                //        Toast.LENGTH_SHORT).show();
                // startActivity<SateliteInfoActivity>()
                //val intent = Intent(this, OfflineMapActivity::class.java)
                //startActivity(intent)

                animSet.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator?) {
                        val intent = Intent(this@MainActivity, SatelliteCN0Activity::class.java)
                        startActivity(intent)
                    }
                })

                animSet.start()
            }

            2 -> {  //Posture Info

                animSet.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator?) {
                        val intent = Intent(this@MainActivity, CarAngleActivity::class.java)
                        startActivity(intent)
                    }
                })

                animSet.start()

            }

            3 -> { //Bluetooth

                animSet.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator?) {
                        //val intent = Intent(this@MainActivity, DeviceScanActivity::class.java)
                        val intent = Intent(this@MainActivity, BluetoothUI::class.java)
                        startActivity(intent)
                    }
                })

                animSet.start()
            }

            4 -> {

                animSet.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator?) {
                        val intent = Intent(this@MainActivity, MapActivity::class.java)
//                intent.putExtra(
//                        BaseTransitionInActivity.EXTRA_TRANSITION, BaseTransitionInActivity.TRANSITION_SLIDE_RIGHT)
//                startActivityWithOptions(intent)
                        startActivity(intent)
                    }
                })

                animSet.start()
            }
        }
    }

    private fun makeIntentFilter(): IntentFilter {
        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED)
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED)
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        return intentFilter
    }

    private val mReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action

            if (BluetoothLeService.ACTION_GATT_CONNECTED == action) {
                runOnUiThread { updateImage(mCenterMenu, R.drawable.turnplate_center_normal) }
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED == action) {
                runOnUiThread { updateImage(mCenterMenu, R.drawable.turnplate_center_unlogin) }
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED == action) {
                var state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
                when (state) {
                    BluetoothAdapter.STATE_OFF -> {
                        Log.e(TAG, "Bluetooth off")

                        //runOnUiThread { updateImage(mCenterMenu, R.drawable.turnplate_center_unlogin) }

                        if (isServcieBond) {
                            unbindService(mServiceConnection)
                            isServcieBond = false
                        }
                    }

                    BluetoothAdapter.STATE_TURNING_OFF -> {
                        Log.e(TAG, "Bluetooth turning off")
                    }

                    BluetoothAdapter.STATE_ON -> {
                        Log.e(TAG, "Bluetooth on")

                        if (!isServcieBond) {
                            val intent = Intent(this@MainActivity, NMEAParserService::class.java)
                            isServcieBond = bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
                        }
                    }

                    BluetoothAdapter.STATE_TURNING_ON -> {
                        Log.e(TAG, "Bluetooth turning on")

                    }
                }
            }
        }
    }

    private fun startActivityWithOptions(intent: Intent) {
        val transitionActivity = ActivityOptions.makeSceneTransitionAnimation(this)
        startActivity(intent, transitionActivity.toBundle())
    }

    override fun itemCenterClick(view: View?) {
        Log.e(TAG, "Circle menu center clicked.")

        var fadeout_anim = ObjectAnimator.ofFloat(view, "fade_out", 1.0f, 0.0f)

        //anim.start()
        fadeout_anim.addUpdateListener { animation -> run {
            var cVal = animation.animatedValue as Float
            view?.alpha = cVal
            view?.scaleX = cVal
            view?.scaleY = cVal
        } }


        var fadein_anim = ObjectAnimator.ofFloat(view, "fade_in", 0.0f, 1.0f)

        fadein_anim.addUpdateListener { animation -> run {
            var cVal = animation.animatedValue as Float
            view?.alpha = cVal
            view?.scaleX = cVal
            view?.scaleY = cVal
        } }

        var animSet = AnimatorSet()
        animSet.setDuration(500)
        //animSet.setInterpolator(LinearInterpolator())
        //animSet.setInterpolator(OvershootInterpolator())
        animSet.setInterpolator(BounceInterpolator())

        animSet.play(fadein_anim).after(fadeout_anim)
        animSet.start()

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ui_main)
        setSupportActionBar(toolbar)

        toolbar.setNavigationIcon(R.mipmap.ic_launcher_round)
        toolbar.setNavigationOnClickListener{view -> run {
            var dialogBuilder = NiftyDialogBuilder.getInstance(this)
            dialogBuilder
                    .withTitle(resources.getString(R.string.exit_app_title))
                    .withMessage(resources.getString(R.string.exit_app_content))
                    .withTitleColor(resources.getColor(R.color.colorPrimaryDark))
                    .withDialogColor(resources.getColor(R.color.colorPrimary))
                    .withEffect(Effectstype.Slidetop)
                    .withButton1Text(resources.getText(R.string.exit_app_direct))
                    .withButton2Text(resources.getText(R.string.exit_app_with_bluetooth_off))
                    .setButton1Click { view -> run {
                        dialogBuilder.dismiss()
                        this.finish()
                    } }
                    .setButton2Click { view -> run {
                        if (mBluetoothAdapter != null) {
                            mBluetoothAdapter!!.disable()
                            dialogBuilder.dismiss()
                            this.finish()
                        }
                    } }
                    .show()
        } }

        id_menulayout.setMenuItemIconsAndTexts(mMainMenuItemImgs, mMainMenuItemTexts)
        id_menulayout.setOnMenuItemClickListener(this)

        mCenterMenu = find(R.id.id_circle_menu_item_center)

//        fab.setOnClickListener { view ->
//            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                    .setAction("Action", null).show()
//        }

//        val toggle = ActionBarDrawerToggle(
//                this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
//        drawer_layout.addDrawerListener(toggle)
//        toggle.syncState()

        //nav_view.setNavigationItemSelectedListener(this)

        //val intent = Intent(this, NMEAParserService::class.java)
        //startService(intent)

        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        mBluetoothAdapter = bluetoothManager.adapter

        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show()
            finish()
            return
        }

    }


    override fun onStart() {
        super.onStart()

        registerReceiver(mReceiver, makeIntentFilter())
    }

    override fun onResume() {
        super.onResume()

        if (!mBluetoothAdapter?.isEnabled()!!) {
            if (!mBluetoothAdapter?.isEnabled()!!) {
                //updateImage(mCenterMenu, R.drawable.turnplate_center_unlogin)
                mCenterMenu.setImageResource(R.drawable.turnplate_center_unlogin)
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
            } else {
                if (!isServcieBond) {
                    val intent = Intent(this, NMEAParserService::class.java)
                    isServcieBond = bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
                }
            }
        } else {
            if (!isServcieBond) {
                val intent = Intent(this, NMEAParserService::class.java)
                isServcieBond = bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
            }
        }
    }

    override fun onPause() {
        super.onPause()

        //unregisterReceiver(mReceiver)
        if (isServcieBond) {
            unbindService(mServiceConnection)
            isServcieBond = false
        }
    }

    override fun onStop() {
        super.onStop()

        unregisterReceiver(mReceiver)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            ToastUtil.show(this, resources.getString(R.string.warn_open_bluetooth))
            finish()
            return
        }
    }

    internal var startTime = 0L
    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            //super.onBackPressed()

            val currentTime = System.currentTimeMillis()
            if (currentTime - startTime >= 2000) {
                Toast.makeText(this, getString(R.string.info_confirm_exit), Toast.LENGTH_SHORT).show()
                startTime = currentTime
            } else {
                finish()
            }
        }
    }

    private var isServcieBond = false
    private var mNMEAParserService: NMEAParserService? = null
    private val mServiceConnection = object : ServiceConnection {

        override fun onServiceConnected(componentName: ComponentName, service: IBinder) {
            Log.e(TAG, "onServiceConnected")
            mNMEAParserService = (service as NMEAParserService.LocalBinder).service

            if (mNMEAParserService != null) {
                var connected = mNMEAParserService!!.connectState
                if (connected!!) {
                    runOnUiThread { updateImage(mCenterMenu, R.drawable.turnplate_center_normal) }
                } else {
                    val sharedPreferences = getSharedPreferences(Constants.BTDevice_Preferences, Context.MODE_PRIVATE)
                    val autoConnect = sharedPreferences.getBoolean(Constants.SP_KEY_BT_IS_AUTO_CONNECT, false)
                    if (autoConnect) {
                        mNMEAParserService!!.autoConnect()
                    }
                }
            }
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            Log.e(TAG, "onServiceDisconnected")
            mNMEAParserService = null
        }
    }

    private fun updateImage(view : ImageView, resId : Int) {
        view.setImageResource(resId)
        itemCenterClick(mCenterMenu)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        //menuInflater.inflate(R.menu.ui_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        when (item.itemId) {
            R.id.action_settings -> return true
            else -> return super.onOptionsItemSelected(item)
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_camera -> {
                // Handle the camera action
            }
            R.id.nav_gallery -> {

            }
            R.id.nav_slideshow -> {

            }
            R.id.nav_manage -> {

            }
            R.id.nav_share -> {

            }
            R.id.nav_send -> {

            }
        }

        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }
}

